package com.kymatrix.kycarbon.xsmd.common.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kymatrix.kycarbon.xsmd.common.mybatisplus.service.ITableFill;
import java.time.LocalDateTime;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MybatisPlusMetaFillHandler implements MetaObjectHandler {
    
    private final ITableFill tableFill;

    private String createTime = "createTime";
    private String updateTime = "updateTime";

    private String creator = "creator";

    private String updater = "updater";

    @Autowired(required = false)
    public MybatisPlusMetaFillHandler(ITableFill tableFill) {
        this.tableFill = tableFill;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        this.strictInsertFill(metaObject, createTime, () -> now, LocalDateTime.class);
        this.strictInsertFill(metaObject, updateTime, () -> now, LocalDateTime.class);
        if (tableFill != null) {
            this.strictInsertFill(metaObject, creator, tableFill::getCreator, String.class);
            this.strictInsertFill(metaObject, updater, tableFill::getUpdater, String.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (getFieldValByName(updateTime, metaObject) != null) {
            this.setFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        }
        if (tableFill != null && getFieldValByName(updater, metaObject) != null) {
            this.setFieldValByName(updater, tableFill.getUpdater(), metaObject);
        }
    }
}
